<template>
  <edit-dialog :centerDialogVisible="visible" :tilte="(isAdd ? '新增' : '编辑') + '分类'" @Cancel="handleCancel"
    @Submit="handleSubmit(goodsTypeFormRef)" :width="dialogWidth">
    <template #content>
      <div>
        <el-form ref="goodsTypeFormRef" :rules="rules" :model="form" label-width="150px">
          <el-form-item label="父级分类">
            <el-input v-model="form.parentName" readonly/>
          </el-form-item>
          <el-form-item label="名称" prop="name">
            <el-input v-model="form.name" maxlength="15" />
          </el-form-item>
          <el-form-item label="本级分类" prop="isCatalogue">
            <el-select v-model="form.isCatalogue" placeholder="请选择" style="width:100%" v-if="isAdd">
              <el-option label="文件夹" value="0" v-if="props.info.level!=3"/>
              <el-option label="工作标准" value="1" v-if="props.info.level!=0"/>
            </el-select>
            <el-select v-model="form.isCatalogue" placeholder="请选择" style="width: 100%" v-else>
              <template v-if="form.isCatalogue==0">
                <el-option label="文件夹" value="0" />
              </template>
              <template v-if="form.isCatalogue==1">
                <el-option label="工作标准" value="1"/>
              </template>

            </el-select>
          </el-form-item>

        </el-form>
      </div>
    </template>
  </edit-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive, defineProps, watch, nextTick, toRaw, computed } from 'vue'
import { useStore } from 'vuex'
import type { FormInstance, FormRules } from 'element-plus'
import { standardClassAppend,standardClassEdit } from '@/api/knowledge/standards'
import editDialog from '@/components/editDialog/index.vue'
import { ElMessage } from 'element-plus'

interface RuleForm {
  name: string;
  isCatalogue: string;
  parentId: number;
  parentName: string;
  catalogueId:number,
  level:number
}

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  isAdd: {
    type: Boolean,
    default: false,
  },
  info: {
    type: Object,
    default: () => null,
  },
})

const emit = defineEmits(['cancel', 'ok'])



const store = useStore()
// 弹窗标题
const dialogWidth = ref('460px')
const goodsTypeFormRef = ref<FormInstance>()
const userInfo = computed(() => store.state.user.userInfo)

const form = reactive<RuleForm>({
  name: '',
  isCatalogue: '',
  parentId: 0,
  parentName: '',
  catalogueId:0,
  level:0
})
const rules = reactive<FormRules<RuleForm>>({
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  isCatalogue: [{ required: true, message: '请选择本级分类', trigger: 'change' }],
})
const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let fetch = standardClassAppend;
      const payload: any = { ...form };
      payload.level=props.info.level?props.info.level:0
      if (!props.isAdd) {
       fetch = standardClassEdit;
        payload.id = props.info.id;
        payload.mender = {
          id: userInfo.value.userId,
          name: userInfo.value.name,
          userName: userInfo.value.userName,
          organId: userInfo.value.organId || '',
          organName: userInfo.value.organName || ''
        }
      } else {
        payload.creator = {
          id: userInfo.value.userId,
          name: userInfo.value.name,
          userName: userInfo.value.userName,
          organId: userInfo.value.organId || '',
          organName: userInfo.value.organName || ''
        }
        payload.level++;
        console.log(payload.level)
        if(payload.level==1&& payload.isCatalogue=='1'){
          ElMessage.info("一级目录下不能新增标准分类");
          return
        }

        if(props.info.level==3&& payload.isCatalogue=='0'){
          ElMessage.info("该目录下不能文件夹");
          return
        }
        //查询子级是否有标准
        if(props.info.children&& payload.isCatalogue=='0'){
          let obj =props.info.children.filter((item)=>{return item.isCatalogue===1})
          if(obj&&obj.length>0){
            ElMessage.info("该目录下不能新增文件夹");
            return
          }
        }
        if(props.info.children&& payload.isCatalogue=='1'&&props.info.children.length>0) {
          let obj = props.info.children.filter((item) => {
            return item.isCatalogue === 0
          })
          if (obj && obj.length > 0) {
            ElMessage.info("该目录下不能新增标准");
            return
          }
        }
      }
      payload.isCatalogue=payload.isCatalogue as number
      //科室id
      payload.catalogueId=payload.catalogueId as number
      console.log(payload);

      const res = await fetch(payload);

      if (res?.code === '1') {
        emit('ok')
        ElMessage.success(!props.isAdd ? '修改成功！' : '新增成功！');
      } else {
        ElMessage.error(res?.message || '操作失败，请重试！');
      }
      console.log('submit!')
    } else {
      console.log('error submit!', fields)
    }
  })
}

const handleCancel = () => {
  emit('cancel')
}

watch(() => props.visible, (val, oldVal) => {
  if (val && val !== oldVal) {
    nextTick(() => {
      if (props.info) {
        if (props.isAdd) {
          // 新增
          console.log(props.info)
          form.name = '';
          form.isCatalogue = '';
          form.parentId = props.info.isCatalogue==-1?"":props.info.id;
          // 层级3和4的时候，默认为2级机构
          form.parentName = props.info.name;

          form.catalogueId = props.info.isCatalogue==-1?props.info.id: props.info.catalogueId;
        } else {
          // 编辑
          const info = toRaw(props.info);
          form.name = info.name;
          form.isCatalogue = info.isCatalogue+"";
          form.catalogueId=info.catalogueId
          form.parentId=info.parentId;
          form.parentName=info.parentName;
        }
      } else {
         form.name = '';
         form.isCatalogue = '';
          form.parentName='';
      }
    })
  }
})
</script>
